<?php
require_once("../../config/config.inc.php");
require_once($CFG_REAL_CLASSES."/json.class.php");
$json = new Services_JSON();

$sEPID   = $SEC->sCorpCD;
$sAction = fn_getParam("strAction","");

if ($sAction == "boxmenu" && fn_getParam('node',"")=='top') { //浏览消息
    //查询未读消息个数
    $sql = "SELECT A.STATUS,COUNT(A.STATUS) AS UNREAD_COUNT ";
    $sql.= "FROM $TABLE_MAIL A WHERE A.EPID='".$sEPID."' ";
    $sql.= "AND A.USERNAME='".$SEC->sUserName."' ";
    $sql.= "AND A.HADREAD='0' ";
    $sql.= "GROUP BY A.STATUS";
    $stmt = $DB->query($sql);
    $aCount = array();
    while ($row = $DB->fetchArray($stmt)) {
        $aCount[$row["STATUS"]] = $row["UNREAD_COUNT"]; 
    }
    $DB->freeResult($stmt);
    
    $boxmenu[] = array('text'=>"收件箱".(isset($aCount[1])?'(<b>'.$aCount[1].'</b>)':''), 
        'id'=>"inboxlist",   'leaf'=>true, 'icon'=>$CFG_VIRT_IMAGES.'/btn/inbox.gif');
    $boxmenu[] = array('text'=>"发件箱", 
        'id'=>"sendboxlist", 'leaf'=>true, 'icon'=>$CFG_VIRT_IMAGES.'/btn/sentbox.gif');
//  $boxmenu[] = array('text'=>"草稿箱", 
//      'id'=>"draftlist",   'leaf'=>true, 'icon'=>$CFG_VIRT_IMAGES.'/btn/draft.gif');
    $boxmenu[] = array('text'=>"垃圾箱".(isset($aCount[4])?'(<b>'.$aCount[4].'</b>)':''), 
        'id'=>"trashlist",   'leaf'=>true, 'icon'=>$CFG_VIRT_IMAGES.'/btn/trash.gif');
    $boxmenu[] = array('text'=>"收藏箱".(isset($aCount[5])?'(<b>'.$aCount[5].'</b>)':''), 
        'id'=>"favoritelist",'leaf'=>true, 'icon'=>$CFG_VIRT_IMAGES.'/btn/expend.gif');

    echo $json->encode($boxmenu);
    unset($boxmenu);
    return;
} else
if ($sAction==ACTION_VIEW) {
    $sMailID = fn_getParam("strMailID","");
    $sql = "SELECT ID,EP_ID,USER_NAME,MESSAGEID,HADREAD ";
    $sql.= "FROM $TABLE_MAIL ";
    $sql.= "WHERE ID='".$sMailID."'";
    $stmt= $DB->query($sql);
    $aMAIL = $DB->fetchArray($stmt);
    $DB->freeResult($stmt);
    
    if ($aMAIL["HADREAD"] == '0') { //将未读改写成已读
        $sql = "UPDATE $TABLE_MAIL SET HADREAD='1' WHERE ID='".$aMAIL["ID"]."'";
        $DB->query($sql);
    }
    
    $sql = "SELECT SENDER,MAILTO,MAILCC,SUBJECT,CONTENT,TYPE,IMPORTANCE,CREATEDATE ";
    $sql.= "FROM $TABLE_MAIL_CONTENT ";
    $sql.= "WHERE ID='".$aMAIL["MESSAGEID"]."'";
    $stmt = $DB->query($sql);
    $aCONTENT = $DB->fetchArray($stmt);
    $DB->freeResult($stmt);
    /*****
    $aMailType        = $DICT->getDictArray("BASE_MAIL_TYPE",false);
    $aMailImportance  = $DICT->getDictArray("BASE_MAIL_IMPORTANCE",false);
    $aCONTENT["TYPE"] = $aMailType[$aCONTENT["TYPE"]];
    
    if ($aCONTENT["IMPORTANCE"] == "1") {
        $aCONTENT["IMPORTANCE"] = "<font color='red'>".$aMailImportance[$aCONTENT["IMPORTANCE"]]."</font>";
    } else {
        $aCONTENT["IMPORTANCE"] = $aMailImportance[$aCONTENT["IMPORTANCE"]];
    }
    *****/
    if ($aMAIL["EP_ID"] != "" && $aMAIL["USER_NAME"] != "") {
        $sSenderId = $aMAIL["EP_ID"]."@".$aMAIL["USER_NAME"];
    } else {
        $sSenderId = "";
    }

    $sReceiver = $aCONTENT["MAILTO"];
    if ($aCONTENT["MAILCC"] != "") {
        $sReceiver .= ' &nbsp; <span><b>抄送：</b></span>'.$aCONTENT["MAILCC"];
    }
    $aMailContent = array("sID"=>$aMAIL["ID"],"sender"=>$aCONTENT["SENDER"],"senderId"=>$sSenderId,
            "receiver"=>$sReceiver,"subject"=>fn_setParam($aCONTENT["SUBJECT"]),
            "content"=>$aCONTENT["CONTENT"],"hRead"=>"1",//"0"标记未读,"1"标记已读
            "sPri"=>$aCONTENT["IMPORTANCE"],"cDate"=>$aCONTENT["CREATEDATE"]);
    
    echo $json->encode($aMailContent);
    unset($aMail);
    unset($aCONTENT);
    unset($aMailContent);
    return;
} else
if ($sAction=="inboxlist" || $sAction=="sendboxlist" || $sAction=="draftlist" 
    || $sAction=="trashlist" || $sAction=="favoritelist") {

    $aMail = array();
    $iStart = fn_getParam("start","0");
    $iPageSize = fn_getParam("limit","20");

    $sqlWhere = "FROM $TABLE_MAIL A INNER JOIN $TABLE_MAIL_CONTENT B ON A.MESSAGEID=B.ID ";
    $sqlWhere.= "WHERE A.EPID='".$sEPID."' ";
    $sqlWhere.= "AND A.USERNAME='".$SEC->sUserName."' ";
    if ($sAction=="inboxlist") { //收件箱
        $sqlWhere.= "AND A.STATUS='1' ";
    } else if ($sAction=="sendboxlist") { //发件箱
        $sqlWhere.= "AND A.STATUS='2' ";
    } else if ($sAction=="draftlist") { //草稿箱
        $sqlWhere.= "AND A.STATUS='3' ";
    } else if ($sAction=="trashlist") { //垃圾箱
        $sqlWhere.= "AND A.STATUS='4' ";
    } else if ($sAction=="favoritelist") { //收藏箱
        $sqlWhere.= "AND A.STATUS='5' ";
    } else {
        echo $json->encode(array('success'=>false,'total'=>"0",'data'=>""));
        return;
    }
    
    $sql = "SELECT A.ID,B.SENDER,A.HADREAD,";
    $sql.= "B.SUBJECT,B.IMPORTANCE,B.CREATEDATE ";
    $sql.= $sqlWhere;
    $sql.= " ORDER BY B.CREATEDATE DESC";
    $sql.= " LIMIT $iStart,$iPageSize";

    //fn_log($sql);
    $iRowCount = $DB->getFirstField("SELECT COUNT(1) ".$sqlWhere);
    $stmt= $DB->query($sql);
    while ($row = $DB->fetchRow($stmt)) {
        $aMail[] = array(
            "sID"=>$row["ID"],"sender"=>($row["HADREAD"]=="0"?"<b>".$row["SENDER"]."</b>":$row["SENDER"]),
            "subject"=>($row["HADREAD"]=="0"?"<b>".$row["SUBJECT"]."</b>":$row["SUBJECT"]),
            "content"=>"ccccc","hRead"=>$row["HADREAD"],//"0"标记未读,"1"标记已读
            "sPri"=>$row["IMPORTANCE"],"cDate"=>($row["HADREAD"]=="0"?"<b>".$row["CREATEDATE"]."</b>":$row["CREATEDATE"])
            );
    }
    $DB->freeResult($stmt);
    if (count($aMail[0])>0) {
        echo $json->encode(array('success'=>true,'total'=>$iRowCount,'data'=>$aMail));
    } else {
        echo $json->encode(array('success'=>true,'total'=>"0",'data'=>""));
    }
    unset($aMail);
    return;
}

//begin transaction control
$conn = $DB->tconnect();
/*******************************************************************
if ($sAction == ACTION_INSERT) { //保存到草稿箱，暂时不实现此功能,2010,03,01
    $sMessageID = fn_getParam("strMessageID","");
    $sSubject   = fn_getParam("strSubject","");
    $sEditor    = fn_getParam("strContent","");
    $sMailType  = "1"; //普通，正常邮件
    $sImportance = fn_getParam("strImportance","");

    $DB->tbegin($conn);
    if ($sMessageID != "") { //had existed, update it
        $sql = "UPDATE $TABLE_MAIL_CONTENT SET SUBJECT='".$sSubject."',CONTENT='".$sEditor;
        $sql.= "',TYPE='".$sMailType."',IMPORTANCE='".$sImportance."',CREATEDATE=NOW() ";
        $sql.= "WHERE ID='".$sMessageID."'";
        $DB->query($sql);

        $sErrCode = true;
        $sErrMesg = "消息已经成功保存到草稿箱。";
    } else {
        //add mail content
        $sql = "INSERT INTO $TABLE_MAIL_CONTENT(MAILTO,MAILCC,SUBJECT,CONTENT,TYPE,IMPORTANCE,CREATEDATE) ";
        $sql.= "VALUES('','','".$sSubject."','".$sEditor."','".$sMailType."','".$sImportance."',NOW())";
        $DB->query($sql);
        $sMessageID = mysql_insert_id();
        if ($sMessageID > 0) {
            $sql = "INSERT INTO $TABLE_MAIL(EPID,USERNAME,MESSAGEID,STATUS,HADREAD) ";
            $sql.= "VALUES('".$sEPID."','".$SEC->sUserName."','".$sMessageID."','3','1')";
            $DB->query($sql);

            $sErrCode = true;
            $sErrMesg = "消息已经成功保存到草稿箱。";
        } else {
            $sErrCode = false;
            $sErrMesg = "消息保存失败，请与网站管理员联系。";
        }
    }
    $DB->tcommit($conn);
    echo $json->encode(array('success'=>$sErrCode,'msg'=>$sErrMesg));
}
*******************************************************/
if ($sAction == ACTION_SAVE) { //send message
    $sTo = fn_getParam("strTo",""); //To&CC id
    $sCC = fn_getParam("strCC","");
    $sMailTo  = fn_getParam("strReceiver",""); //To&CC name
    $sMailCC  = fn_getParam("strCCer","");
    $sSender  = fn_getParam("strSender","");
    $sSubject = fn_getParam("strSubject","");
    $sEditor  = fn_getParam("strContent","");
    $sMessageID = ""; //fn_getParam("strMessageID","");
    $sMailType  = "1";
    $sImportance= fn_getParam("strImportance","");

    $DB->tbegin($conn);
    if ($sMessageID != "") { //更新草稿箱消息，暂时不实现
        $sql = "UPDATE $TABLE_MAIL_CONTENT SET SUBJECT='".$sSubject."',CONTENT='".$sEditor;
        $sql.= "',TYPE='".$sMailType."',IMPORTANCE='".$sImportance."',CREATEDATE=NOW(),";
        $sql.= "SENDER='".$sSender."',MAILTO='".$sMailTo."',MAILCC='".$sMailCC."' ";
        $sql.= "WHERE ID='".$sMessageID."'";
        $DB->tquery($sql,$conn);
        //保存到发件箱
        $sql = "UPDATE $TABLE_MAIL SET STATUS='2' "; //EPID,USERNAME发件人企业id和用户名
        $sql.= "WHERE EPID='".$sEPID."' AND USERNAME='".$SEC->sUserName."' ";
        $sql.= "AND MESSAGEID='".$sMessageID."'";
        $DB->tquery($sql,$conn);
    } else {
        //add mail content
        $sql = "INSERT INTO $TABLE_MAIL_CONTENT(SENDER,MAILTO,MAILCC,SUBJECT,CONTENT,TYPE,IMPORTANCE,CREATEDATE) ";
        $sql.= "VALUES('".$sSender."','".$sMailTo."','".$sMailCC."','".$sSubject."','".$sEditor."','".$sMailType."','".$sImportance."',NOW())";
        $DB->tquery($sql,$conn);
        $sMessageID = "".mysql_insert_id();
        //保存到发件箱
        $sql = "INSERT INTO $TABLE_MAIL(EPID,USERNAME,MESSAGEID,STATUS,HADREAD) ";
        $sql.= "VALUES('".$sEPID."','".$SEC->sUserName."','".$sMessageID."','2','1')";
        $DB->tquery($sql,$conn);
    }
    if ($sMessageID != "") {
        if ($sCC != "") {
            $sTo = $sTo."#".$sCC;
        }
        $aTo = explode("#",$sTo);
        for ($i=0; $i<count($aTo); $i++) {
            if (strpos($aTo[$i],"@") > 0) {
                $aaTo = explode("@",$aTo[$i]);
                $sEPID1 = $aaTo[0];
                $sUserName1 = $aaTo[1];
            } else {
                $sEPID1 = $sEPID;
                $sUserName1 = $aTo[$i];
            } //EP_ID,USER_NAME接收人企业id和用户名
            $sql = "INSERT INTO $TABLE_MAIL(EPID,USERNAME,EP_ID,USER_NAME,MESSAGEID,STATUS,HADREAD) ";
            $sql.= "SELECT EP_ID,USER_NAME,'".$sEPID."','".$SEC->sUserName."','".$sMessageID;
            $sql.= "','1','0' FROM $TABLE_FRIEND ";
            $sql.= "WHERE EPID='".$sEPID."' AND USERNAME='".$SEC->sUserName."' ";
            $sql.= "AND EP_ID='".$sEPID1."' AND USER_NAME='".$sUserName1."' ";
            $sql.= "UNION ";
            $sql.= "SELECT EPID,USERNAME,'".$sEPID."','".$SEC->sUserName."','".$sMessageID;
            $sql.= "','1','0' FROM $TABLE_EP_USER ";
            $sql.= "WHERE EPID='".$sEPID1."' AND USERNAME='".$sUserName1."'";
            $DB->tquery($sql,$conn);
            fn_log($sql);
            fn_log($sTo);
        }
        $sErrCode = true;
        $sErrMesg = "消息已经成功发送，同时保存到发件箱。";
    } else {
        $sErrCode = false;
        $sErrMesg = "消息发送失败，请与网站管理员联系。";
    }
    $DB->tcommit($conn);
    echo $json->encode(array('success'=>$sErrCode,'msg'=>$sErrMesg));
} else
if ($sAction==ACTION_DELETE) {
    $sMailList = fn_getParam("strMailList","");
    $aMailID   = explode("#",$sMailList);

    $DB->tbegin($conn);
    for ($i=0; $i<count($aMailID); $i++) {
        $sql = "SELECT MESSAGEID FROM $TABLE_MAIL WHERE ID='".$aMailID[$i]."'";
        $sMessageID = $DB->getFirstField($sql);
        $sql = "SELECT COUNT(ID) FROM $TABLE_MAIL WHERE MESSAGEID='".$sMessageID."'";
        $iMailCount = $DB->getFirstField($sql);
        if ($iMailCount == 1) { //剩下最后一个时，则将内容删除
            $sql = "DELETE FROM $TABLE_MAIL_CONTENT WHERE ID='".$sMessageID."'";
            $DB->tquery($sql,$conn);
        }
        $sql = "DELETE FROM $TABLE_MAIL WHERE ID='".$aMailID[$i]."'";
        $DB->tquery($sql,$conn);
    }
    $sResult = "您选择的消息已经成功删除。";
    $DB->tcommit($conn);
    echo $json->encode(array('success'=>true,'msg'=>$sResult));
} else
if ($sAction=="FAVORITE") { //FAVORITE Mail
    $sMailList = fn_getParam("strMailList","");
    $aMailID   = explode("#",$sMailList);

    $DB->tbegin($conn);
    for ($i=0; $i<count($aMailID); $i++) {
        $sql = "UPDATE $TABLE_MAIL SET STATUS='5' WHERE ID='".$aMailID[$i]."'";
        $DB->tquery($sql,$conn);
    }
    $sResult = "您选择的消息已经成功收藏。";
    $DB->tcommit($conn);
    echo $json->encode(array('success'=>true,'msg'=>$sResult));
} else
if ($sAction=="MARKREAD") { //Mark Mail read or unread.
    $sReadFlag = fn_getParam("strReadFlag","0");
    $sMailList = fn_getParam("strMailList","");
    $aMailID   = explode("#",$sMailList);

    $DB->tbegin($conn);
    for ($i=0; $i<count($aMailID); $i++) {
        $sql = "UPDATE $TABLE_MAIL SET HADREAD='".$sReadFlag."' WHERE ID='".$aMailID[$i]."'";
        $DB->tquery($sql,$conn);
    }
    $sResult = "您选择的消息已经成功标记。";
    $DB->tcommit($conn);
    echo $json->encode(array('success'=>true,'msg'=>$sResult));
}
//close connection at last
$DB->tclose($conn);

?>